//
//  ServiceHTSensor.swift
//  home
//
//  Created by Yun Zeng on 2019/1/31.
//  Copyright © 2019 Yun Zeng. All rights reserved.
//

import UIKit

class ServiceHTSensor {
    var service: Service
    // 温湿度值
    var humidity: HMCharacteristic
    var temperature: HMCharacteristic
    
    init?(service: Service) {
        if service.type != HMServiceType.htSensor.rawValue {
            return nil
        }
        guard let temperature = service.findCharacteristic(type: .currentTemperature) else {
            return nil
        }
        guard let humidity = service.findCharacteristic(type: .currentRelativeHumidity) else {
            return nil
        }
        self.service = service
        self.temperature = temperature
        self.humidity = humidity
    }

    var temperatureValue: Float {
        get {
            if let value = temperature.value?.toValueFloat() {
                return value
            }
            return 0.0
        }
    }
    
    var humidityValue: Int {
        get {
            if let value = humidity.value?.toValueFloat() {
                return Int(value)
            }
            return 0
        }
    }
}

// cell 显示协议
extension ServiceHTSensor: ServiceCellDelegate {
    var icon: UIView {
        let imageView = UIImageView(frame: ServiceCellView.iconSize)
        imageView.image = UIImage(named: "service-" + self.service.icon! + "-online")
        return imageView
    }
    
    var name: String {
        if self.service.name != "" {
            return self.service.name
        }
        return "请命名"
    }
    
    var state: Service.State {
        return self.service.state
    }
    
    var desc: String {
        if self.state == .offline {
            return "离线"
        }
        if self.state == .update {
            return "正在更新"
        }
        return String(format: "%0.1f° %d%%", self.temperatureValue, self.humidityValue)
    }
    
    func toggle() -> HomeAction? {
        return nil
    }
    
    var room: String {
        if let r = self.service.room {
            return r.name
        }
        return "默认房间"
    }
    
}

